<script setup name="Dept" lang="ts">
import { DeleteOutlined, FormOutlined, PlusSquareOutlined, SearchOutlined } from '@ant-design/icons-vue'
import type { PaginationProps } from 'ant-design-vue'
import { addDept, delDept, getDept, listDept, listDeptExcludeChild, updateDept } from '@/api/system/dept'
import type { DeptForm, DeptQuery, DeptVO } from '@/api/system/dept/types'
import type { UserVO } from '@/api/system/user/types'
import { listUserByDeptId } from '@/api/system/user'
import { handleTree, parseTime } from '~/utils/ruoyi.ts'

interface DeptOptionsType {
  deptId: number | string
  deptName: string
  children: DeptOptionsType[]

}

const { proxy } = getCurrentInstance() as ComponentInternalInstance
const { sys_normal_disable } = toRefs<any>(proxy?.useDict('sys_normal_disable'))
const message = useMessage()
const modal = useModal()
const deptList = ref<DeptVO[]>([])
const loading = ref(true)
const deptOptions = ref<DeptOptionsType[]>([])
const isExpandAll = ref(false)
const expandRows = ref<string[] | number[]>([])
const deptUserList = ref<UserVO[]>([])

const dialog = reactive<DialogOption>({
  visible: false,
  title: '',
})

const deptTableRef = ref()
const queryFormRef = ref()
const deptFormRef = ref()

const initFormData: DeptForm = {
  deptId: undefined,
  parentId: undefined,
  deptName: undefined,
  orderNum: 0,
  leader: undefined,
  phone: undefined,
  email: undefined,
  status: '0',
}
const data = reactive<PageData<DeptForm, DeptQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    deptName: undefined,
    status: undefined,
  },
  rules: {
    parentId: [{ required: true, message: '上级部门不能为空', trigger: 'blur' }],
    deptName: [{ required: true, message: '部门名称不能为空', trigger: 'blur' }],
    orderNum: [{ required: true, message: '显示排序不能为空', trigger: 'blur' }],
    email: [{ type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }],
    phone: [{ pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/, message: '请输入正确的手机号码', trigger: 'blur' }],
  },
})

const { queryParams, form, rules } = toRefs<PageData<DeptForm, DeptQuery>>(data)

/** 查询菜单列表 */
async function getList() {
  loading.value = true
  const res = await listDept(queryParams.value)
  const data = handleTree<DeptVO>(res.data, 'deptId')
  if (data)
    deptList.value = data

  loading.value = false
}

/** 查询当前部门的所有用户 */
async function getDeptAllUser(deptId: any) {
  if (deptId !== null && deptId !== '' && deptId !== undefined) {
    const res = await listUserByDeptId(deptId)
    deptUserList.value = res.data
  }
}

/** 取消按钮 */
function cancel() {
  reset()
  dialog.visible = false
}

/** 表单重置 */
function reset() {
  form.value = { ...initFormData }
  deptFormRef.value?.resetFields()
}

/** 搜索按钮操作 */
function handleQuery() {
  getList()
}

/** 新增按钮操作 */
async function handleAdd(row?: DeptVO) {
  reset()
  const res = await listDept()
  const data = handleTree<DeptOptionsType>(res.data, 'deptId')
  if (data) {
    deptOptions.value = data
    if (row && row.deptId)
      form.value.parentId = row?.deptId

    dialog.visible = true
    dialog.title = '添加部门'
  }
}

/** 修改按钮操作 */
async function handleUpdate(row: DeptVO) {
  reset()
  // 查询当前部门所有用户
  getDeptAllUser(row.deptId)
  const res = await getDept(row.deptId)
  form.value = res.data
  const response = await listDeptExcludeChild(row.deptId)
  const data = handleTree<DeptOptionsType>(response.data, 'deptId')
  if (data) {
    deptOptions.value = data
    if (data.length === 0) {
      const noResultsOptions: DeptOptionsType = {
        deptId: res.data.parentId,
        deptName: res.data.parentName,
        children: [],
      }
      deptOptions.value.push(noResultsOptions)
    }
  }
  dialog.visible = true
  dialog.title = '修改部门'
}

/** 提交按钮 */
function submitForm() {
  deptFormRef.value?.validate().then(async () => {
    form.value.deptId ? await updateDept(form.value) : await addDept(form.value)
    message.success('操作成功')
    dialog.visible = false
    await getList()
  })
}

const pagination: PaginationProps = reactive({
  pageSize: 10,
  current: 1,
  total: 0,
  showSizeChanger: false,
  showQuickJumper: false,
  showTotal: (total: number) => `总计：${total}条数据`,
  onChange(current: number, pageSize: number) {
    pagination.current = current
    pagination.pageSize = pageSize
    queryParams.value.pageNum = current
    queryParams.value.pageSize = pageSize
    getList()
  },
})

/** 删除按钮操作 */
async function handleDelete(row: DeptVO) {
  modal.confirm({
    title: `是否确认删除名称为"${row.deptName}"的数据项?`,
    onOk: async () => {
      await delDept(row.deptId)
      await getList()
      message.success('删除成功')
    },
  })
}

onMounted(() => {
  getList()
})
</script>

<template>
  <div class="p-2 bh-table">
    <a-card class="mb-20px">
      <div>
        <a-form ref="queryFormRef" label-align="left" :colon="false">
          <div class="flex items-center gap-10px">
            <a-input
              v-model:value="queryParams.deptName" placeholder="请输入部门名称"
              class="grow"
              @press-enter="handleQuery"
            >
              <template #prefix>
                <SearchOutlined />
              </template>
            </a-input>
            <div class="bh-table-title-suffix">
              <div class="bh-table-title-suffix-content">
                <a-button type="primary" @click="handleAdd">
                  新增
                </a-button>
              </div>
            </div>
          </div>
        </a-form>
      </div>
    </a-card>
    <a-card>
      <a-table
        ref="deptTableRef"
        v-model:expandedRowKeys="expandRows"
        :loading="loading"
        :data-source="deptList"
        :pagination="false"
        row-key="deptId"
        :default-expand-all-rows="isExpandAll"
      >
        <a-table-column data-index="deptName" title="部门名称" width="260" />
        <a-table-column data-index="orderNum" align="center" title="排序" width="200" />
        <a-table-column data-index="status" align="center" title="状态" width="100">
          <template #default="{ record }">
            <bh-dict-tag :options="sys_normal_disable" :value="record.status" />
          </template>
        </a-table-column>
        <a-table-column title="创建时间" align="center" data-index="createTime" width="200">
          <template #default="{ record }">
            <span>{{ parseTime(record.createTime) }}</span>
          </template>
        </a-table-column>
        <a-table-column fixed="right" align="center" title="操作">
          <template #default="{ record }">
            <a-tooltip content="修改" placement="top">
              <a-button v-hasPermi="['system:dept:edit']" type="link" @click="handleUpdate(record)">
                <FormOutlined />
              </a-button>
            </a-tooltip>
            <a-tooltip content="新增" placement="top">
              <a-button v-hasPermi="['system:dept:add']" type="link" @click="handleAdd(record)">
                <PlusSquareOutlined />
              </a-button>
            </a-tooltip>
            <a-tooltip content="删除" placement="top">
              <a-button v-hasPermi="['system:dept:remove']" type="link" @click="handleDelete(record)">
                <DeleteOutlined />
              </a-button>
            </a-tooltip>
          </template>
        </a-table-column>
      </a-table>
    </a-card>

    <a-modal v-model:open="dialog.visible" :mask-closable="false" :keyboard="false" :title="dialog.title" destroy-on-close append-to-bod width="600px">
      <a-form ref="deptFormRef" :model="form" :rules="rules" layout="vertical">
        <div class="pl-8px pr-8px">
          <a-row :gutter="16">
            <a-col v-if="form.parentId !== 0" :span="24">
              <a-form-item label="上级部门" name="parentId">
                <a-tree-select
                  v-model:value="form.parentId"
                  :tree-data="deptOptions"
                  tree-default-expand-all
                  :field-names="{ value: 'deptId', label: 'deptName', children: 'children' }"
                  placeholder="选择上级部门"
                />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="部门名称" name="deptName">
                <a-input v-model:value="form.deptName" placeholder="请输入部门名称" />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="显示排序" name="orderNum">
                <a-input-number v-model:value="form.orderNum" :controls="false" style="width: 100%" controls-position="right" :min="0" />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="部门状态">
                <a-radio-group v-model:value="form.status">
                  <a-radio v-for="dict in sys_normal_disable" :key="dict.value" :value="dict.value" :label="dict.value">
                    {{ dict.label }}
                  </a-radio>
                </a-radio-group>
              </a-form-item>
            </a-col>
          </a-row>
        </div>
      </a-form>
      <template #footer>
        <div class="dialog-footer">
          <a-button @click="cancel">
            取 消
          </a-button>

          <a-button type="primary" @click="submitForm">
            确 定
          </a-button>
        </div>
      </template>
    </a-modal>
  </div>
</template>

<style scoped lang="less">
@import "@/components/bh-table/index.less";
:deep(.ant-table-empty){
  .ant-table-cell{
    background: #f0f2f5;
  }
  .ant-table-placeholder:hover > td{
    background: #f0f2f5 !important;
  }
}
</style>
